/*
Copyright (c) 2014, Rick Wilson
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of 'Taareekah' nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import worldgeneration.WorldGenerator;
import worldgeneration.Util;
import world.GenericTerrainMap;
import util.BMPFile;
import util.BitmapPixelShader;
import java.util.logging.Level;
import java.util.logging.Logger;
import parameters.*;

public class Shader extends BitmapPixelShader {
    private GenericTerrainMap elevation;
    public Shader(GenericTerrainMap elevation) {
        this.elevation = elevation;
    }
    public int[] getColorAtPoint(int x, int y) {
        float value = elevation.getValueAtPoint(x, y);
        int[] ret = new int[3];
        if (value > 255.0f || value < 0.0f) {
            Logger.getLogger(Shader.class.getName()).log(Level.INFO, "invalid value");
            return ret;
        }
        if (value == 0.0f) {
            ret[0] = ret[1] = 0;
            ret[2] = 255;
        } else {
            if (value < 1.0f) {
                ret[0] = ret[1] = ret[2] = 1;
            } else {
                ret[0] = ret[1] = ret[2] = value.toInteger();
            }
            
        }
        
        return ret;
    }
}

def toRange(int val, int size) {
    return (2.0f * (val.toFloat().div(size.toFloat()))) - 1.0f;
}
def toRangeFloat(float val, int size) {
    return (2.0 * (val.toDouble().div(size.toDouble()))) - 1.0;
}
void normalizeTerrain(float value, GenericTerrainMap map, int size) {
        float currentMin, currentMax;
        float height;

        currentMin = 100.0f;
        currentMax = 0.0f;

        //find the min/max values of the height fTemptemptempBuffer
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                if (map.getValueAtPoint(i, j).isNaN()) {
                    continue;
                }
                if (map.getValueAtPoint(i, j) > currentMax) {
                    currentMax = map.getValueAtPoint(i, j);
                } else if (map.getValueAtPoint(i, j) < currentMin) {
                    currentMin = map.getValueAtPoint(i, j);
                }
            }
        }
        Logger.getLogger("normalize terrain").log(Level.INFO, "max: " + currentMax + " min: " + currentMin);

        //find the range of the altitude
        if (currentMax <= currentMin) {
            Logger.getLogger("normalize terrain").log(Level.INFO, "max less than min");
            return;
        }

        height = currentMax - currentMin;

        //scale the values to a range of 0-255
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                if (map.getValueAtPoint(i, j).isNaN()) {
                    map.setValueAtPoint(i, j, 0.0f);
                } else {
                    if ((((map.getValueAtPoint(i, j) - currentMin).div(height)) * value).toFloat() <= 0.0f) {
                        Logger.getLogger("normalize terrain").log(Level.INFO, "X: " + i + "; Y: " + j + " = " + (((map.getValueAtPoint(i, j) - currentMin).div(height)) * value).toFloat());
                    }
                    map.setValueAtPoint(i, j, (((map.getValueAtPoint(i, j) - currentMin).div(height)) * value).toFloat());
                }
                
            }
        }
    }
	
def modifyElevation(GenericTerrainMap elevation, int size, double power, double threshold, float np, int radius) {
    for (int x = 0; x < size; x++) {
        for (int y = 0; y < size; y++) {
            float x_norm = toRange(x, size);
            float y_norm = toRange(y, size);
            float cur_value = elevation.getValueAtPoint(x, y);
            double cur_val_norm = toRangeFloat(cur_value, 255);
            
            double x_sq_plus_y_sq = ((x_norm * x_norm).toDouble() + (y_norm * y_norm).toDouble());
            
            double multiplied = cur_val_norm * Math.exp(-x_sq_plus_y_sq.div(16.0)) - x_sq_plus_y_sq;
            
            if (multiplied < threshold) {
                elevation.setValueAtPoint(x, y, Float.NaN);
            } else {
                elevation.setValueAtPoint(x, y, Math.pow(multiplied, power).toFloat());
            }
            
        }
    }
    
    normalizeTerrain(255f, elevation, size);
    //Util.smooth(elevation, np, radius);
    elevation.setShader(new Shader(elevation));
}
int radius = scriptparameters.getChild("smoothradius").getValueAsInt();
float np = scriptparameters.getChild("smoothnp").getValueAsFloat();
double power = scriptparameters.getChild("power").getValueAsDouble();
double threshold = scriptparameters.getChild("threshold").getValueAsDouble();
modifyElevation(worldgenerator.getMap("elevation"), worldgenerator.getWorldSize(), power, threshold, np, radius);